package cn.biwysh.exam.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class EncodingFilter implements Filter {
	protected FilterConfig filterConfig;
	private String targetEncoding = "utf-8";

	public void init(FilterConfig config) throws ServletException
	{
		this.filterConfig = config;
		this.targetEncoding = config.getInitParameter("encoding");
	}

	public void doFilter(ServletRequest srequest, ServletResponse sresponse,
			FilterChain chain) throws IOException, ServletException
	{
		HttpSession session = ((HttpServletRequest) srequest).getSession(true);
		 if (session.getAttribute("user")==null && ((HttpServletRequest)srequest).getRequestURI().indexOf("login.do") == -1 && ((HttpServletRequest)srequest).getRequestURI().indexOf("/gl/") > -1)
		 {
			 ((HttpServletResponse)sresponse).sendRedirect(((HttpServletRequest)srequest).getContextPath()+"/gl/login.do");
		 }
		 else
		 {
			srequest.setCharacterEncoding(targetEncoding);
			sresponse.setCharacterEncoding(targetEncoding);
			chain.doFilter(srequest, sresponse);
		}
	}

	public void setFilterConfig(final FilterConfig filterConfig)
	{
		this.filterConfig = filterConfig;
	}

	public void destroy()
	{
		this.filterConfig = null;
	}
}
